import Hls, {
    FragmentLoaderConstructor, 
    FragmentLoaderContext, 
    LoaderConfiguration,
    LoaderCallbacks
  } from 'hls.js'

// import cacheIndexdDB from './cacheIndexdDB';
import cachesAny from './cachesAny';

export default class extends Hls.DefaultConfig.loader  {
    private cache: cachesAny;
  
    async load(
      context: FragmentLoaderContext,
      config: LoaderConfiguration,
      callbacks: LoaderCallbacks<FragmentLoaderContext>,
    ) {
      const {url} = context;
      // console.log({context, config, callbacks});
  
      if(!this.cache){
        this.cache = new cachesAny()
      }
  
      const resp = await this.cache.get(url)
      
      if(resp){
        // console.log(resp);
        
        callbacks.onSuccess({data: resp,url}, null, context as any, null)
        return;
      }
    
      super.load(context, config, {
        ...callbacks,
        onSuccess: async (response, stats, context, networkDetails) => {
          // console.log('load:', response, stats, context, networkDetails);
  
          await this.cache.put(url, response.data);
  
          callbacks.onSuccess(response, stats, context as any, networkDetails)
        }
      });
    }
  }